package com.lzk.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class LoginCheckFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //获取请求地址
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String uri = request.getRequestURI();
        //判断请求路径是否带有受限资源
        if(uri.endsWith("login")||uri.endsWith("register")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取到请求头和响应头
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        //从请求头中获取到token
        String token = request.getHeader("token");
        //判断token是否为空
        if (StringUtils.isEmpty(token)){//为空
            try {
                //设置响应格式和编码以及内容
                response.setContentType("application/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                HashMap<Object, Object> map = new HashMap<>();
                map.put("success",false);
                map.put("message","noLogin");
                //将map转为json格式数据
                String date = JSONObject.toJSONString(map);
                //响应到前端
                writer.write(date);

                //阻止后续filter
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
